package com.deepinblog.oosdemo;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created by louisyuu on 2019/6/12 下午2:54
 */
public class ImageSizeValidator implements ConstraintValidator<ImageSize, Object> {



    private int size;


    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            //not null validate
            return true;
        }
        if (value instanceof MultipartFile[]) {
            for (MultipartFile file : (MultipartFile[]) value) {
                return onSize(file);
            }
        }
        if (value instanceof MultipartFile) {
            return onSize((MultipartFile) value);
        }
        return false;
    }

    @Override
    public void initialize(ImageSize imageSize) {

        this.size = imageSize.size();

    }

    private String getSuffix(MultipartFile file) {
        return file.getContentType().split("/")[1];
    }

    private boolean onSize(MultipartFile mf) {
        File file;
        try {
            file = File.createTempFile(getSuffix(mf), String.valueOf(System.currentTimeMillis()));
            FileUtils.copyInputStreamToFile(mf.getInputStream(), file);
            BufferedImage bufferedImage = ImageIO.read(file);
            if (bufferedImage == null) {
                return false;
            }
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
//            if (width > this.width) {
//                return false;
//            }
//            if (height > this.height) {
//                return false;
//            }
            if (mf.getSize() >= this.size) {
                return false;
            }
        } catch (IOException e) {
            return false;
        }
        return true;
    }

}
